#include "widget.h"
#include "ui_widget.h"

Widget::Widget(QWidget *parent)
    : QWidget(parent)
    , ui(new Ui::Widget)
    , server(new QTcpServer(this))
{
    ui->setupUi(this);
    QHostAddress address = QHostAddress::LocalHost;
    quint16 port = 1234;
    server->listen(address, port);
    if(server->isListening())
    {
        status = "Listening...";
    }
    else
    {
        status = "Rest...";
    }
    ui->PTedit_status->appendPlainText(status);
    connect(server, SIGNAL(newConnection), this, SLOT(onNewConnection));
}

Widget::~Widget()
{
    server->close();
    delete ui;
}

void Widget::onNewConnection()
{
    QTcpSocket *client_socket = server->nextPendingConnection();
    QHostAddress address = client_socket->peerAddress();
    quint16 port = client_socket->peerPort();
    QString text = "connected: " + address.toString() + "\t" + QString::number(port) + "\t" +"已连接";
    ui->PTedit_status->appendPlainText(text);
    // 做正事
    clients.append(client_socket);
    connect(client_socket, SIGNAL(disconnect), this, SLOT(onDisConnect));
    connect(client_socket, SIGNAL(readyRead), this, SLOT(onReadyRead));

}

void Widget::onDisConnect()
{
    QTcpSocket *client_socket = qobject_cast<QTcpSocket*>(sender()); // 获取发送信号的客户端
   if (client_socket)
   {
       clients.removeOne(client_socket); // 从列表中移除
       QHostAddress address = client_socket->peerAddress();
       quint16 port = client_socket->peerPort();
       QString text = "disconnected: " + address.toString() + "\t" + QString::number(port) + "\t" +"断开连接";
       ui->PTedit_status->appendPlainText(text);
       client_socket->deleteLater(); // 销毁对象
   }
}

void Widget::onReadyRead()
{
    QTcpSocket *client_socket = qobject_cast<QTcpSocket*>(sender());  // 获取当前客户端
    while (client_socket->bytesAvailable()) // 确保有数据可读
    {
        QByteArray data = client_socket->readAll(); // 读取所有数据
        QHostAddress address = client_socket->peerAddress();
        quint16 port = client_socket->peerPort();
        QString msg = QString::fromUtf8(data); // 转换为字符串
        QString text = "recieve: " + address.toString() + "\t" + QString::number(port) + "\t" +"发送消息\n\t" + msg;
        ui->PTedit_status->appendPlainText(text);
    }
}

/* 服务器发送数据给所有客户端 */
void Widget::send_data()
{

    QString msg = "服务器发送的数据";
    QByteArray data = msg.toUtf8();
    // 遍历所有客户端发送数据
    for (QTcpSocket *client : clients)
    {
        client->write(data);
    }
    ui->PTedit_status->appendPlainText("send: " + msg);
}
